package com.linc.concurrency.semaphore;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Semaphore;

public class BoundedHashSet<T> {
  private final Set<T> set;
  private final Semaphore sem;

  public BoundedHashSet(int bound) {
    set = new HashSet<>();
    sem = new Semaphore(bound);
  }

  public boolean add(T o) throws InterruptedException {
    sem.acquire();
    boolean added = false;
    try {
      added = set.add(o);
      return added;
    } finally {
      if (!added) sem.release();
    }
  }

  public boolean remove(T o) {
    boolean removed = set.remove(o);
    if (removed) sem.release();
    return removed;
  }
}
